package dao;

import text.leaveBean;
import utils.JDBCUtil;

import java.sql.*;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

public class FindAllDao {

    public List<leaveBean> findAll() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        List<leaveBean> leaves = new ArrayList<leaveBean>();
        try {
            conn = JDBCUtil.getConnection();
            String sql = "select * from leavemessage";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            //防止空指针
            if (!rs.next()) {
                return null;
            }
            //让rs的指针回到第一的位置
            rs.beforeFirst();

            while (rs.next()) {
                leaveBean leaveBean = new leaveBean();
                //将留言，时间和用户存入list的集合中
                leaveBean.setLeave(rs.getString("leaveMessage"));
                leaveBean.setTime(rs.getString("time"));
                leaveBean.setUser(rs.getString("user"));
                leaves.add(leaveBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(rs, stmt, conn);
            //将list集合反转
            Collections.reverse(leaves);
            return leaves;
        }
    }
}
